﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMS.Common;
using WMS.Model;
using WMS.Repository.IRepository;
using WMS.Service.IService;
using static Dm.net.buffer.ByteArrayBuffer;

namespace WMS.Service
{
    public class UserService : BaseServices<UserModel>, IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IAvatarService _avatarService;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IDepartmentRepository _departmentRepository;
        public UserService(IBaseRepository<UserModel> repository,
            ILogger<BaseServices<UserModel>> logger,
            IAvatarService avatarService,
             IUnitOfWork unitOfWork,
              IDepartmentRepository departmentRepository,
            IUserRepository userRepository) : base(repository, logger)
        {
            _unitOfWork = unitOfWork;
            _avatarService = avatarService;
            _userRepository = userRepository;
            _departmentRepository = departmentRepository;
        }

        /// <summary>
        /// 分页查询用户列表
        /// </summary>
        public async Task<PageResult<UserWithAvatarDto>> GetUserPagedListAsync(UserQueryRequest request)
        {
            try
            {
                if (request.PageSize > 100)
                {
                    request.PageSize = 100;
                }

                // 1. 获取原始分页数据
                PageResult<UserModel> model = await _userRepository.GetUserPagedListAsync(request);

                // 2. 转换为DTO
                var userDtos = new List<UserWithAvatarDto>();

                if (model?.Data != null && model.Data.Any())
                {
                    // 提取所有用户的UserCode
                    var userCodes = model.Data.Select(u => u.UserCode).ToList();

                    // 批量获取头像URL
                    var avatarUrls = await _avatarService.GetAvatarUrlsByUserCodesAsync(userCodes);

                    // 提取所有部门ID
                    var departmentIds = model.Data.Select(u => u.Department).Distinct().ToList();

                    // 批量获取部门名称
                    var departmentNames = await _departmentRepository.GetDepartmentNamesBatchAsync(departmentIds);

                    // 转换数据并赋值头像URL
                    userDtos = model.Data.Select(user => new UserWithAvatarDto
                    {
                        Id = user.Id,
                        UserCode = user.UserCode,
                        Account = user.Account,
                        Realname = user.Realname,
                        Email = user.Email,
                        Phone = user.Phone,
                        Status = user.Status,
                        DepartmentName = departmentNames.TryGetValue(user.Department, out var deptName) ? deptName : "无部门",
                        AvatarUrl = avatarUrls.TryGetValue(user.UserCode, out var avatarUrl) ? avatarUrl : null
                    }).ToList();
                }

                // 3. 返回新的分页结果
                return new PageResult<UserWithAvatarDto>
                {
                    PageIndex = model.PageIndex,
                    PageSize = model.PageSize,
                    TotalCount = model.TotalCount,
                    TotalPages = model.TotalPages,
                    Data = userDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户分页查询失败");
                throw;
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        public async Task<(bool Success, string Message)> AddUserAsync(AddUserModelDto user)
        {
            try
            {
                UserModel model = await _userRepository.GetAccountAsync(user.Account);
                if (model != null)
                {
                    return (false, "账号已存在！");
                }
                if (string.IsNullOrEmpty(user.Password))
                {
                    user.Password = MD5Helper.EncryptPassword("123456");
                }
                else
                {
                    user.Password = MD5Helper.EncryptPassword(user.Password);
                }

                UserModel usermodel = new UserModel()
                {
                    Account = user.Account,
                    Password = user.Password,
                    UserCode = GuidHelper.GenerateWithoutDash(),
                    Realname = user.Realname,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    Status = 1,
                    Department = 0
                };


                bool result = await _repository.AddAsync(usermodel);
                if (result)
                {
                    return (true, "添加成功！");
                }
                else
                {
                    return (false, "添加失败，请重新尝试！");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加用户失败 - 账号: {user?.Account}");
                throw;
            }
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        public async Task<(bool Success, string Message)> UpdateUserAsync(UpdateUserModelDto user, IFormFile file)
        {
            try
            {
                // 1. 先进行业务验证
                var model = await _repository.GetAsync(user.Id);
                if (model == null)
                    return (false, "用户不存在！");

                // 2. 使用事务执行数据更新
                var success = await _unitOfWork.ExecuteTransactionAsync(async () =>
                {
                    // 更新用户基本信息
                    model.Realname = user.Realname;
                    model.Phone = user.Phone;
                    model.Email = user.Email;
                    model.UpdateTime = DateTime.Now;
                    model.Status = user.Status;
                    model.Department = user.Department;

                    if (!string.IsNullOrEmpty(user.Password))
                    {
                        model.Password = MD5Helper.EncryptPassword(user.Password);
                    }

                    // 更新用户信息
                    return await _repository.UpdateAsync(model);
                });

                if (!success.Success)
                    return (false, "更新用户信息失败");

                // 3. 处理头像上传（放在事务外，避免文件操作影响数据库事务）
                if (file != null && file.Length > 0)
                {
                    try
                    {
                        var avatarResult = await _avatarService.UploadUserAvatarAsync(user.UserCode, file);
                        if (!avatarResult.Success)
                        {
                            _logger.LogWarning($"用户头像上传失败 - 用户ID: {user.Id}, 错误: {avatarResult.Message}");
                            // 返回成功，但提示头像上传失败
                            return (true, "用户信息修改成功，但头像上传失败");
                        }
                    }
                    catch (Exception avatarEx)
                    {
                        _logger.LogError(avatarEx, $"头像上传异常 - 用户ID: {user.Id}");
                        // 返回成功，但提示头像上传异常
                        return (true, "用户信息修改成功，但头像上传异常");
                    }
                }

                // 4. 清除缓存
                await _avatarService.ClearAvatarCacheAsync(user.UserCode);

                return (true, "修改成功！");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改用户失败 - 用户ID: {user?.Id}");
                return (false, $"修改失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 启用停用用户
        /// </summary>
        public async Task<(bool Success, string Message)> UpdateUserStatusAsync(long id)
        {
            try
            {
                var user = await _repository.GetAsync(id);
                if (user == null)
                {
                    return (false, "用户不存在！");
                }

                user.Status = (byte)(user.Status == 0 ? 1 : 0);
                bool result = await _repository.UpdateAsync(user);
                if (result)
                {
                    return (true, "操作成功！");
                }
                else
                {
                    return (false, "操作失败，请重新尝试！");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新用户状态失败 - 用户ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 批量启用停用用户
        /// </summary>
        public async Task<(bool Success, string Message)> UpdateUsersStatusAsync(List<long> ids)
        {
            try
            {
                var successCount = 0;
                var notFoundIds = new List<long>();
                var failedIds = new List<long>();

                foreach (var id in ids)
                {
                    try
                    {
                        var user = await _repository.GetAsync(id);
                        if (user == null)
                        {
                            notFoundIds.Add(id);
                            continue;
                        }

                        user.Status = (byte)(user.Status == 0 ? 1 : 0);
                        bool result = await _repository.UpdateAsync(user);
                        if (result)
                        {
                            successCount++;
                        }
                        else
                        {
                            failedIds.Add(id);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"处理用户状态失败 - 用户ID: {id}");
                        failedIds.Add(id);
                    }
                }

                var message = $"操作完成：成功 {successCount} 个，失败 {failedIds.Count} 个，未找到 {notFoundIds.Count} 个";
                return (successCount > 0, message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量更新用户状态失败 - 用户数量: {ids?.Count ?? 0}");
                throw;
            }
        }

        /// <summary>
        /// 获取用户下拉框
        /// </summary>
        public async Task<object> GetUserDropdownBoxAsync()
        {
            try
            {
                var userModels = await _userRepository.GetUserDropdownBoxAsync();
                return userModels.Select(x => new { x.Id, x.Realname }).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户下拉框失败");
                throw;
            }
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<(bool Success, string Message)> UpdateUserPwdAsync(long id, string password, string NewPassword)
        {
            try
            {
                UserModel user = await _repository.GetById(id);
                if (user == null)
                {
                    return (false, "用户不存在！");
                }

                password = MD5Helper.EncryptPassword(password);
                if (password != user.Password)
                {
                    return (false, "密码不正确！");
                }

                string md5NewPassword = MD5Helper.EncryptPassword(NewPassword);
                if (user.Password == md5NewPassword)
                {
                    return (false, "旧密码和新密码相同！");
                }

                user.Password = md5NewPassword;

                if (await _repository.UpdateAsync(user))
                {
                    return (true, "修改成功！");
                }
                else
                {
                    return (true, "修改失败！");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改用户密码失败");
                throw;
            }
        }
    }
}